package com.creditcmsplt.util;

import java.io.File;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;

public class HttpUtil {

	private static Logger log = LoggerFactory.getLogger(HttpUtil.class);
	
	public static final String METHOD_POST = "post";
	public static final String METHOD_GET = "get";
	public static final String METHOD_DELETE = "delete";

	/**
	 * 发送http restful接口请求，json 字符提交,文件上传请转换base64
	 * 
	 * @param url
	 *            请求url
	 * @param methodType
	 *            请求模式 （post、get等）
	 * @param params：请求参数
	 * @param jsonStr
	 *            请求单参数
	 * @return
	 */
	public static String execuateHttp(String url, String methodType, Map<String, Object> params, String jsonStr) {
		log.info("execuateHttp:"+url+" param:"+params+"  "+jsonStr);
		SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
		requestFactory.setConnectTimeout(30000);
		requestFactory.setReadTimeout(30000);
		RestTemplate restTemplate = new RestTemplate();
		try {
			ResponseEntity<String> resp = null;
			HttpHeaders httpHeaders = new HttpHeaders();
			httpHeaders.add("Content-Type", "application/json; charset=UTF-8");
			HttpEntity requestEntity = null;
			if (jsonStr != null && !jsonStr.equals("")) {
				requestEntity = new HttpEntity<String>(jsonStr, httpHeaders);
			} else {
				requestEntity = new HttpEntity<Map<String, Object>>(params, httpHeaders);
			}
			if ("post".equals(methodType)) {
				resp = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
			} else if ("get".equals(methodType)) {
				resp = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
			}
			return resp.getBody().toString();
		} catch (Exception e) {
			log.error("",e);
		}
		return null;
	}

	/**
	 * 发送http restful接口请求，form-data 支持文件上传
	 * 
	 * @param url
	 *            请求url
	 * @param methodType
	 *            请求模式 （post、get等）
	 * @param params：请求参数
	 * @param jsonStr
	 *            请求单参数
	 * @return
	 */
	public static String execuateHttpFile(String url, String methodType, Map<String, Object> params,
			Map<String, String> files) {
		log.info("execuateHttp:"+url+" param:"+params+"  "+files);
		SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
		requestFactory.setConnectTimeout(30000);
		requestFactory.setReadTimeout(30000);
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity<String> resp = null;
		try {
			HttpHeaders httpHeaders = new HttpHeaders();
			httpHeaders.add("Content-Type", "multipart/form-data; charset=UTF-8");
			HttpEntity requestEntity = null;
			MultiValueMap<String, Object> multiValueMap=new LinkedMultiValueMap<String, Object>();
			if (params!=null) {
				Set<String> formkey = params.keySet();
				for (Iterator iterator = formkey.iterator(); iterator.hasNext();) {
					String string = (String) iterator.next();
					multiValueMap.add(string, params.get(string));
				} 
			}
			if (files!=null) {
				Set<String> filekey = files.keySet();
				for (Iterator iterator = filekey.iterator(); iterator.hasNext();) {
					String string = (String) iterator.next();
					FileSystemResource resource = new FileSystemResource(new File(files.get(string)));
					multiValueMap.add(string, resource);
				}
				multiValueMap.add("Content-Type", "image/jpeg");
			}
			requestEntity = new HttpEntity<MultiValueMap<String, Object>>(multiValueMap,httpHeaders);
			if ("post".equals(methodType)) {
				resp = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
			} else if ("get".equals(methodType)) {
				resp = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
			}
			return resp.getBody().toString();
		} catch (Exception e) {
			log.error("",e);
		}
		return null;
	}

	public static String execuateHttpBasicAuth(String url, String methodType, String user, String password,
			Map<String, String> params, String jsonStr) throws Exception {
		log.info("execuateHttp:"+url+" param:"+params+"  "+jsonStr);
		SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
		requestFactory.setConnectTimeout(30000);
		requestFactory.setReadTimeout(30000);
		RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder().basicAuthorization(user, password);
		RestTemplate restTemplate = restTemplateBuilder.build();
		ResponseEntity<String> resp = null;
		try {
			HttpHeaders httpHeaders = new HttpHeaders();
			httpHeaders.add("Content-Type", "application/json; charset=UTF-8");
			HttpEntity requestEntity = null;

			if (jsonStr != null && !jsonStr.equals("")) {
				requestEntity = new HttpEntity<String>(jsonStr, httpHeaders);
			} else {
				requestEntity = new HttpEntity<Map<String, String>>(params, httpHeaders);
			}
			if ("post".equals(methodType)) {
				resp = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
			} else if ("get".equals(methodType)) {
				resp = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
			}
			return resp.getBody().toString();
		} catch (Exception e) {
			log.error("",e);
		}
		return null;
	}
}
